<?php
// ----------------------------------------------------------
// * @Copyright @ 2011-2020 By HuaXiaXinCai
// ----------------------------------------------------------
// * @Author Yang Changwu<800334@qq.com> 2016-12-12
// ----------------------------------------------------------
/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);
error_reporting(0); //错误提示关闭

use \GatewayWorker\Lib\Gateway;
use \Workerman\Lib\Timer;
use \GatewayWorker\Lib\Db;
use \Controller\Redis;
use \Controller\Core;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events {
    /**
     * 当businessWorker进程启动时触发。每个进程生命周期内都只会触发一次
     * @param int $businessWorker
     */
    public static function onWorkerStart($businessWorker) {
        if ($businessWorker->id === 3) {
            //广播倒记时
            Core::PushPeriod();
            Core::Notice();
        }
    }

    /**
     * 当客户端连上时触发
     * @param int $client_id
     */
    public static function onConnect($client_id) {
        //self::PushPeriod($client_id);
        Timer::add(30, function()use($client_id) {
            //踢掉登录异常连接
            if (!$_SESSION['uid']) {
                Core::SendMsg(1024,array('method'=>'Closed'),2,$client_id);
                Gateway::closeClient($client_id);
            }
        });
    }

    /**
     * 有消息时
     * @param int $client_id
     * @param string $message
     */
    public static function onMessage($client_id, $message) {
        $data = json_decode($message, true);
        Core::WriteLog('receive', $message);
        //发送数据处理
        if (!$data) {
            return Core::SendMsg(1002, $data);
        }
        $data = Core::ChangCase($data);
        
        foreach ($data as $k => $v){
            $data[$k] = addslashes(trim($v));
        }

        if (!($data['api'] && $data['method'])) {
            return Core::SendMsg(1002, $data);
        }
        if (file_exists(__DIR__ . '/Controller/' . $data['api'] . '.php')) {
            $class_name = '\Controller\\' . $data['api'];
            $class = new $class_name;
            call_user_func_array(array($class, $data['method']), array($data, $client_id));
        } else {
            return Core::SendMsg(1005, $data);
        }
    }

    /**
     * 当用户断开连接时
     * @param integer $client_id 用户id
     */
    public static function onClose($client_id) {
        if ($_SESSION['uid']) {
            //更新在线时间(秒)
            //$arr = ['dateline' => $_SESSION['dateline'] + (time() - $_SESSION['lasttime'])];
            //Db::instance('db')->update('sz_user')->cols($arr)->where("uid=" . $_SESSION['uid'])->query();
        }
        unset($_SESSION);
    }
}